﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using Assesment.Library;
using Assesment.Library.DomainObject.Administration.Catalog;
using Assesment.Library.Enum;
using Assesment.Library.Interfaces;
using SIPO.Library.DomainObject.Administration.Catalog;

namespace Assesment.Library.DataAccess.Administration.Catalog
{
    public partial class KeyBehaviourRepo : ISearchable<KeyBehaviour>
    {
        public object SelectScalar(SQL.Function.Aggregate function, string column, string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {

                        case SQL.Function.Aggregate.Count:
                            //sbQuery.AppendFormat("SELECT COUNT({0}) FROM master.KeyBehaviour {1}", column,parameters);
                            cmd.CommandText = "SP_KeyBehaviour_GridPage_CountData";
                            break;

                        default:
                            // do nothing 
                            break;
                    }

                    //cmd.CommandText = sbQuery.ToString();
                    //cmd.CommandType = CommandType.Text;

                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@column", SqlDbType.VarChar).Value = column;
                    cmd.Parameters.Add("@param", SqlDbType.VarChar).Value = parameters;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public List<KeyBehaviour> GetList(int pageSize, int currentPage, string sortName, string sortOrder, string parameters)
        {
            List<KeyBehaviour> tt = new List<KeyBehaviour>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);

                    cmd.CommandText = "SP_KeyBehaviour_GridPage";
                    cmd.Parameters.Add("@startRow", SqlDbType.Int).Value = startRow;
                    cmd.Parameters.Add("@endRow", SqlDbType.Int).Value = endRow;
                    cmd.Parameters.Add("@sortName", SqlDbType.VarChar).Value = sortName;
                    cmd.Parameters.Add("@sortOrder", SqlDbType.VarChar).Value = sortOrder;
                    cmd.Parameters.Add("@param", SqlDbType.VarChar).Value = parameters;
                    cmd.CommandType = CommandType.StoredProcedure;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                KeyBehaviour t = new KeyBehaviour(true);
                                t.KeyBhvID = dr[KeyBehaviour.Fields.KeyBhvID] == DBNull.Value ? 0 : int.Parse(dr[KeyBehaviour.Fields.KeyBhvID].ToString());
                                t.CompetencyID = dr[KeyBehaviour.Fields.CompetencyID] == DBNull.Value ? (int?)null : int.Parse(dr[KeyBehaviour.Fields.CompetencyID].ToString());
                                t.LevelCompetencyID = dr[KeyBehaviour.Fields.LevelCompetencyID] == DBNull.Value ? (int?)null : int.Parse(dr[KeyBehaviour.Fields.LevelCompetencyID].ToString());
                                t.CreatedDate = dr[KeyBehaviour.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[KeyBehaviour.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[KeyBehaviour.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[KeyBehaviour.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[KeyBehaviour.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[KeyBehaviour.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[KeyBehaviour.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[KeyBehaviour.Fields.UpdatedBy].ToString();


                                t.LevelCompetency.Level = dr[LevelCompetency.Fields.Level] == DBNull.Value ? (short?)null : short.Parse(dr[LevelCompetency.Fields.Level].ToString());
                                t.Competency.CompetncyDesc = dr[Competency.Fields.CompetncyDesc] == DBNull.Value ? string.Empty : dr[Competency.Fields.CompetncyDesc].ToString();
                                t.Competency.GroupCompetency = dr[Competency.Fields.GroupCompetency] == DBNull.Value ? string.Empty : dr[Competency.Fields.GroupCompetency].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        

        public bool Save(KeyBehaviour domain, List<KeyBehaviourDetail> list)
        {
            bool result = false;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {

                conn.Open();
                SqlTransaction txn = conn.BeginTransaction();
                try
                {
                    #region Insert Data KeyBehaviour

                    //string query = "INSERT INTO master.Competency(RowStatus, CompetncyDesc, Definition, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate) VALUES(@RowStatus, @CompetncyDesc, @Definition, @CreatedBy, @CreatedDate, @UpdatedBy, @UpdatedDate)";
                    SqlCommand cmd = new SqlCommand("SP_Competency_Insert", conn);
                    cmd.CommandText = "SP_KeyBehaviour_Insert";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@CompetencyID", SqlDbType.Int).Value = (object)domain.CompetencyID ?? DBNull.Value;
                    cmd.Parameters.Add("@LevelCompetencyID", SqlDbType.Int).Value = (object)domain.LevelCompetencyID ?? DBNull.Value;
                    cmd.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = (object)domain.CreatedDate ?? DBNull.Value;
                    cmd.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = (object)domain.CreatedBy ?? DBNull.Value;
                    cmd.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)domain.UpdatedDate ?? DBNull.Value;
                    cmd.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)domain.UpdatedBy ?? DBNull.Value;
         
                    cmd.Transaction = txn;
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();

                    #endregion

                    #region Insert Data Level Competency


                    #region Ambil KeyBehaviourID


                    SqlCommand cmdKeyBehaviour = new SqlCommand("SP_KeyBehaviour_SelectBy_CreatedByCreatedDate", conn);
                    cmdKeyBehaviour.CommandType = CommandType.StoredProcedure;
                    cmdKeyBehaviour.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = domain.CreatedBy;
                    cmdKeyBehaviour.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = domain.CreatedDate;
                    cmdKeyBehaviour.Transaction = txn;
                    var BehaviourID = cmdKeyBehaviour.ExecuteScalar();
                    int resultBehaviourID = BehaviourID == DBNull.Value ? 0 : int.Parse(BehaviourID.ToString());
                    cmdKeyBehaviour.Dispose();

                    #endregion


                    foreach (KeyBehaviourDetail data in list)
                    {

                        
                        SqlCommand cmdKeyBehaviourDetail = new SqlCommand("SP_KeyBehaviourDetail_Insert", conn);
                        cmdKeyBehaviourDetail.CommandType = CommandType.StoredProcedure;
                        cmdKeyBehaviourDetail.Parameters.Add("@KeyBehaviourID", SqlDbType.Int).Value = resultBehaviourID;
                        cmdKeyBehaviourDetail.Parameters.Add("@KeyBehaviourName", SqlDbType.VarChar).Value = (object)data.KeyBehaviourName ?? DBNull.Value;
                        cmdKeyBehaviourDetail.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = (object)data.CreatedDate ?? DBNull.Value;
                        cmdKeyBehaviourDetail.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = (object)data.CreatedBy ?? DBNull.Value;
                        cmdKeyBehaviourDetail.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)data.UpdatedDate ?? DBNull.Value;
                        cmdKeyBehaviourDetail.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)data.UpdatedBy ?? DBNull.Value;

                        cmdKeyBehaviourDetail.Transaction = txn;
                        cmdKeyBehaviourDetail.ExecuteNonQuery();
                        cmdKeyBehaviourDetail.Dispose();
                    }

                    #endregion


                    result = true;
                    txn.Commit();

                }
                catch (Exception ex)
                {
                    txn.Rollback();
                    throw (ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open) conn.Close();
                }
            }

            return result;
        }

        public bool Update(KeyBehaviour domain, List<KeyBehaviourDetail> list)
        {
            bool result = false;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {

                conn.Open();
                SqlTransaction txn = conn.BeginTransaction();
                try
                {
                    #region UPDATE Data KeyBehaviour

                    //string query = "UPDATE master.Competency SET RowStatus = @RowStatus, CompetncyDesc = @CompetncyDesc, Definition = @Definition, UpdatedBy = @UpdatedBy, UpdatedDate = @UpdatedDate WHERE ComptID = @ComptID";
                    SqlCommand cmd = new SqlCommand("SP_KeyBehaviour_Update", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@KeyBhvID", SqlDbType.Int).Value = domain.KeyBhvID;
                    cmd.Parameters.Add("@CompetencyID", SqlDbType.Int).Value = (object)domain.CompetencyID ?? DBNull.Value;
                    cmd.Parameters.Add("@LevelCompetencyID", SqlDbType.Int).Value = (object)domain.LevelCompetencyID ?? DBNull.Value;
                    cmd.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)domain.UpdatedDate ?? DBNull.Value;
                    cmd.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)domain.UpdatedBy ?? DBNull.Value;

                   

                    cmd.Transaction = txn;
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();

                    #endregion


                    #region Delete Detail Berdasar KeyBehaviourID

                    SqlCommand cmdDeleteKey = new SqlCommand("SP_KeyBehaviourDetail_DeleteBy_KeyBehaviourID", conn);
                    cmdDeleteKey.CommandType = CommandType.StoredProcedure;
                    cmdDeleteKey.Parameters.Add("@KeyBehaviourID", SqlDbType.Int).Value = domain.KeyBhvID;
                    cmdDeleteKey.Transaction = txn;
                    cmdDeleteKey.ExecuteNonQuery();
                    cmdDeleteKey.Dispose();

                    #endregion

                    #region Insert Data KeyBehaviourDetail


                    foreach (KeyBehaviourDetail data in list)
                    {


                        SqlCommand cmdKeyBehaviourDetail = new SqlCommand("SP_KeyBehaviourDetail_Insert", conn);
                        cmdKeyBehaviourDetail.CommandType = CommandType.StoredProcedure;
                        cmdKeyBehaviourDetail.Parameters.Add("@KeyBehaviourID", SqlDbType.Int).Value = domain.KeyBhvID;
                        cmdKeyBehaviourDetail.Parameters.Add("@KeyBehaviourName", SqlDbType.VarChar).Value = (object)data.KeyBehaviourName ?? DBNull.Value;
                        cmdKeyBehaviourDetail.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = (object)data.CreatedDate ?? DBNull.Value;
                        cmdKeyBehaviourDetail.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = (object)data.CreatedBy ?? DBNull.Value;
                        cmdKeyBehaviourDetail.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)data.UpdatedDate ?? DBNull.Value;
                        cmdKeyBehaviourDetail.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)data.UpdatedBy ?? DBNull.Value;

                        cmdKeyBehaviourDetail.Transaction = txn;
                        cmdKeyBehaviourDetail.ExecuteNonQuery();
                        cmdKeyBehaviourDetail.Dispose();
                    }



                    #endregion


                    result = true;
                    txn.Commit();

                }
                catch (Exception ex)
                {
                    txn.Rollback();
                    throw (ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open) conn.Close();
                }
            }

            return result;
        }

        public bool DeleteWithLevel(int key)
        {
            bool result = false;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {

                conn.Open();
                SqlTransaction txn = conn.BeginTransaction();
                try
                {


                    #region Delete Table KeyBehaviourDetail



                    SqlCommand cmdLevel = new SqlCommand("SP_KeyBehaviourDetail_DeleteBy_KeyBehaviourID", conn);
                    cmdLevel.CommandType = CommandType.StoredProcedure;
                    cmdLevel.Parameters.Add("@KeyBehaviourID", SqlDbType.Int).Value = key;

                    cmdLevel.Transaction = txn;
                    cmdLevel.ExecuteNonQuery();
                    cmdLevel.Dispose();

                    #endregion

                    #region Delete Table KeyBehaviour


                    SqlCommand cmd = new SqlCommand("SP_KeyBehaviour_Delete", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@KeyBhvID", SqlDbType.Int).Value = key;

                    cmd.Transaction = txn;
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();

                    #endregion


                    result = true;
                    txn.Commit();

                }
                catch (Exception ex)
                {
                    txn.Rollback();
                    throw (ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open) conn.Close();
                }
            }

            return result;
        }


        public KeyBehaviour GetByCompetencyID_LevelCompetencyID(int CompetencyID, int LevelCompetencyID)
        {
            KeyBehaviour t = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    //cmd.CommandText = "SELECT KeyBhvID, CompetencyID, LevelCompetencyID, CreatedDate, CreatedBy, UpdatedDate, UpdatedBy FROM master.KeyBehaviour WHERE KeyBhvID = @KeyBhvID";
                    cmd.CommandText = "SP_KeyBehaviour_SelectBy_CompetencyID_AND_LevelCompetencyID";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@CompetencyID", SqlDbType.Int).Value = CompetencyID;
                    cmd.Parameters.Add("@LevelCompetencyID", SqlDbType.Int).Value = LevelCompetencyID;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                t = new KeyBehaviour();
                                t.KeyBhvID = dr[KeyBehaviour.Fields.KeyBhvID] == DBNull.Value ? 0 : int.Parse(dr[KeyBehaviour.Fields.KeyBhvID].ToString());
                                t.CompetencyID = dr[KeyBehaviour.Fields.CompetencyID] == DBNull.Value ? (int?)null : int.Parse(dr[KeyBehaviour.Fields.CompetencyID].ToString());
                                t.LevelCompetencyID = dr[KeyBehaviour.Fields.LevelCompetencyID] == DBNull.Value ? (int?)null : int.Parse(dr[KeyBehaviour.Fields.LevelCompetencyID].ToString());
                                t.CreatedDate = dr[KeyBehaviour.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[KeyBehaviour.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[KeyBehaviour.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[KeyBehaviour.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[KeyBehaviour.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[KeyBehaviour.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[KeyBehaviour.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[KeyBehaviour.Fields.UpdatedBy].ToString();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return t;
        }
    }
}
